import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute, Router } from '@angular/router';
import { forkJoin, from } from 'rxjs';

import { PutSaveService } from './put-save.service';
import { PurchasePlanApplyService } from '../purchase-plan-apply/purchase-plan-apply.service'
import { PurchaseOrderAddService } from '../purchase-order-add/purchase-order-add.service'

@Component({
  selector: 'app-put-save',
  templateUrl: './put-save.component.html',
  styleUrls: ['./put-save.component.scss']
})

export class PutSaveComponent implements OnInit {
  
  // 路由传参
  routeParams: any ={};
  // formParams
  formParams: any = {
    warehousingNumber: '', // 入库单号
    warehousing: {
      purchaseNumber: '', // 采购单号
      whPutId: '', // 仓库id
      remark: '', // 备注
      state: '0', // 状态(0 草稿 2 已通知 3 已完成 4 已关闭)
    },
    list: []
  }
  // 保存loading
  subLoading: boolean = false;

  // 采购单下拉list
  purchaseLists: any = [];
  // 采购单下拉list
  warehouseLists: any = [];

  // 表格行宽arry
  nzWidthConfig: string[] = ['50px','100px','250px','200px','150px','150px','150px','150px','150px','160px','150px','120px'];
  purchaseTableLoading: boolean = false;
  // 采购单列表
  purchaseTables: any = [];
  // 已选列表
  selectedTables: any = [];
  // 详情已选table
  backupSelectedTables: any = [];

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private PutSaveService: PutSaveService,
    private PurchasePlanApplyService: PurchasePlanApplyService,
    private PurchaseOrderAddService: PurchaseOrderAddService,
    private message: NzMessageService
  ) {
    this.activatedRoute.params.subscribe((res: any) => {
      console.log('路由参数', res);
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    let postArr: any = [this.PutSaveService.getPurchaseList(), this.PutSaveService.getWhList()];
    forkJoin(postArr).subscribe((list: any) => {
      let purchaseArrs = list[0];
      let warehouseArrs = list[1];

      // 采购单下拉list
      if (purchaseArrs.code == 0 && purchaseArrs.data.records && purchaseArrs.data.records.length) {
        this.purchaseLists = purchaseArrs.data.records.filter((item: any) => { return item.state == 2 || item.state == 4; })
      }

      // 仓库下拉list
      if (warehouseArrs.code == 0 && warehouseArrs.data.records && warehouseArrs.data.records.length) {
        this.warehouseLists = warehouseArrs.data.records.filter((item: any) => { return item.state == 1; })
      }

      // 编辑跳转
      if (this.routeParams.id != '0') {
        this.getDetailsData();
      }

      // 生成采购单跳转
      if (this.routeParams.type && this.routeParams.type == 'create') {
        this.formParams.warehousing.purchaseNumber = this.routeParams.number;

        let selectedId = this.purchaseLists.filter((item: any) => { return item.purchaseNumber == this.routeParams.number })[0].id;
        this.getPurchaseTable(selectedId);
      }
    })
  }

  // 获取详情
  getDetailsData() {
    this.PutSaveService.details(this.routeParams.id).subscribe((res: any) => {
      if (res.code == 0) {
        const { list, warehousing }: any = res.data;
        this.formParams.warehousingNumber = warehousing.warehousingNumber; // 入库单号
        this.formParams.warehousing.purchaseNumber = warehousing.purchaseNumber; // 采购单号
        this.formParams.warehousing.whPutId = warehousing.whPutId; // 入库仓库ID
        this.formParams.warehousing.remark = warehousing.remark; // 备注
        this.formParams.warehousing.state = warehousing.state; // 状态

        // 用作判断编辑时当前项是否可点击
        this.backupSelectedTables = list.map((item: any) => { return item.planId });

        list.map((item: any) => item.isShow = 1);
        this.selectedTables = list;
        // 获取采购单table
        this.purchaseChange(warehousing.purchaseNumber);
      }
    })
  }

  /**
   * 采购单Table
   * @param id 采购单ID
   */
  getPurchaseTable(id: any) {
    this.purchaseTableLoading = true;
    this.PutSaveService.getPurchaseDetails(id).subscribe((res: any) => {
      this.purchaseTableLoading = false;

      if (res.code == 0 && res.data.list && res.data.list.length) {
        this.purchaseTables = res.data.list.map((item: any) => {
          let obj: any = {};
          if (item.state != -1) {
            obj = {
              ...item,
              isShow: 0 // 用作操作采购 && 取消采购
            }
          }
          return obj
        })

        if (this.routeParams.id) {
          let tempList = this.selectedTables.map((tag: any) => {
            return tag.planId;
          })
          this.purchaseTables.forEach((ele: any) => {
            if (tempList.includes(ele.planId)) {
              ele.isShow = 1;
            }
          });
        }
      } else {
        this.message.error(res.message || '数据请求失败');
      }
    }, (error: any) => {
      this.purchaseTableLoading = false;
      this.purchaseTables = [];
    })
  }

  // 采购单change
  purchaseChange(ev: any) {
    let selectedId = this.purchaseLists.filter((item: any) => { return item.purchaseNumber == ev })[0].id;
    this.getPurchaseTable(selectedId);
  }

  /**
   * 全部采购 & 清空全部
   * @param num 
   */
  selectAll(num: number) {
    if (num == 0) {
      let isAdd = this.purchaseTables.every((item: any) => {
        return item.isShow == 1;
      })
      if (isAdd) {
        this.message.warning('当前无可添加项');
        return
      }

      this.purchaseTables.forEach((ele: any, index: number) => {
        let diffNum = ele.purchaseNumber - ele.frozenNumber - ele.stockNumber;
        if (ele.isShow == 0 && (diffNum > 0 || this.backupSelectedTables.includes(ele.planId))) {
          this.singleChoice(ele, index);
        }
      });
    } else {
      this.selectedTables = [];
      this.purchaseTables.map((item: any) => item.isShow = 0);
    }
  }
  /**
   * 单个采购 || 取消
   * @param item 
   * @param index 
   */
  singleChoice(item: any, index: number) {
    // isShow 0：可添加状态，1：移除状态
    switch (item.isShow) {
      case 0:
        this.purchaseTables[index].isShow = 1;
        this.selectedTables.push({
          ...item,
          isShow: 1,
          planDetailsId: item.planDetailsId || item.id,
          number: item.maxStockNumber
        });
        break;
      case 1:
        let topDeleteIndex = this.purchaseTables.findIndex((ele: any) => ele.planId == item.planId);
        let bomDeleteIndex = this.selectedTables.findIndex((ele: any) => ele.planId == item.planId);
        
        this.purchaseTables[topDeleteIndex].isShow = 0;
        this.selectedTables.splice(bomDeleteIndex, 1);
        break;
    }
  }

  // 保存
  preserData() {
    if (!this.verifData()) {
      return
    }

    let params = {
      warehousing: this.formParams.warehousing,
      list: JSON.parse(JSON.stringify(this.selectedTables))
    }
    this.subLoading = true;

    if (this.routeParams.id == '0') {
      params.list.map((item: any) => { delete item.id });
      
      this.PutSaveService.save(params).subscribe((res: any) => {
        this.subLoading = false;
        this.subResult(res);
      }, (error: any) => {
        this.subLoading = false;
        this.message.error(error);
      })
    } else {
      params.warehousing.id = this.routeParams.id;

      this.PutSaveService.update(params).subscribe((res: any) => {
        this.subLoading = false;
        this.subResult(res);
      }, (error: any) => {
        this.subLoading = false;
        this.message.error(error);
      })
    }
  }

  // submit success
  subResult(res: any) {
    if (res && res.code == 0) {
      this.message.success('保存成功');
      this.router.navigate(['/stock/put']);
    } else {
      this.message.error(res.message || '保存失败');
    }
  }

  // 出库数量 回车聚焦到下一个
  onKeydownEnter(ev: any, id: number) {
    const { keyCode } = ev
    if (keyCode == 13) {
      document.getElementById(`putSaveInputID${id + 1}`)?.focus()
    }
  }

  // 验证
  verifData() {
    if (!this.formParams.warehousing.purchaseNumber) {
        this.message.warning("请选择采购单号");
        return false;
    }
    if (!this.formParams.warehousing.whPutId) {
        this.message.warning("请选择入库仓库");
        return false;
    }
    if (!this.selectedTables.length) {
        this.message.warning("请选择入库内容");
        return false;
    }
    
    for (let i = 0; i < this.selectedTables.length; i++) {
      const { number } = this.selectedTables[i];
      if (!number) {
          this.message.warning("入库数量不能为空");
          return;
      }
    }
    return true;
  }

  /**
   * 合计
   * @param fields 合计项字段
   * @param array 合计项数组
   */
  getCombinedTotal(fields: string, array: any[]) {
    let sum = 0;
    if (array.length) {
      sum = array.reduce((total, item) => {
        return total + item[fields];
      }, 0);
    }
    return sum;
  }
}
